package com.scwatch.core.repository.impl;

import com.alibaba.fastjson.JSONObject;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;
import com.scwatch.common.orm.Limitable;
import com.scwatch.common.orm.QuerydslUtils;
import com.scwatch.core.domain.Invite;
import com.scwatch.core.domain.dsl.QInvite;
import com.scwatch.core.repository.plus.InviteDaoPlus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import javax.persistence.EntityManager;
import java.util.List;

public class InviteDaoImpl implements InviteDaoPlus {
    @Override
    public List<Invite> findList(JSONObject json, Limitable limitable) {
        JPAQuery<Invite> query = new JPAQuery<Invite>(this.em);
        QInvite invite =QInvite.invite;
        this.predicate(query,invite,json);
        return QuerydslUtils.list(query, invite, limitable);
    }

    @Override
    public Page<Invite> findPage(JSONObject json, Pageable pageable) {
        JPAQuery<Invite> query = new JPAQuery<Invite>(this.em);
        QInvite invite =QInvite.invite;
        this.predicate(query,invite,json);
        return QuerydslUtils.page(query, invite, pageable);
    }

    @Override
    public void flushAndRefresh(Invite entity) {
        em.flush();
        em.refresh(entity);
    }

    /**
     * 拼接 查询条件
     */
    protected void predicate(JPAQuery<Invite> query, QInvite qInvite, JSONObject json) {
        query.from(qInvite);
        BooleanBuilder exp = new BooleanBuilder();
        String invitationCode = json.getString("invitationCode");
        String invitePeople = json.getString("invitePeople");
        Integer id = json.getInteger("id");
        if (StringUtils.isBlank(invitationCode)) {
            exp.and(qInvite.invitationCode.eq(invitationCode));
        }
        if (StringUtils.isBlank(invitePeople)) {
            exp.and(qInvite.invitePeople.eq(invitePeople));
        }
        query.where(exp);
    }

    private EntityManager em;

    public EntityManager getEm() {
        return em;
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }
}
